﻿﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Parsers
{
    public class DeviceMessageInfoReadingsParser : AbstractMessageParser<IDeviceMessageInfoReadings>, IDeviceMessageInfoReadingsParser
    {
        public DeviceMessageInfoReadingsParser() : base(new DeviceMessageInfoReadings())
        {
        }
        public override IDeviceMessageInfoReadings Parser(ReadOnlySpan<byte> bytes)
        {
            IDeviceMessageInfoReadings model = new DeviceMessageInfoReadings();
            byte readingCount = bytes[0];
            
            // 直接创建正确大小的数组，避免内存池污染问题
            model.ReadingArray = new IDeviceMessageInfoReading[readingCount];
            int currentIndex = 1;
            
            for (int i = 0; i < readingCount; i++)
            {
                byte stateCount = bytes[currentIndex + 2];
                int stateDataLength = 1;
                int stateIndex = currentIndex + 3;
                
                for (int j = 0; j < stateCount; j++)
                {
                    byte type = bytes[stateIndex + 1];
                    int valueLength = DeviceMessageUtilities.GetValueLength(bytes, stateIndex + 1);
                    stateDataLength += 2 + valueLength;
                    stateIndex += 2 + valueLength;
                }
                
                int totalReadingLength = 2 + stateDataLength;
                model.ReadingArray[i] = DeviceMessageSerializerProvider.InfoReadingV1Par.Parser(
                    bytes.Slice(currentIndex, totalReadingLength));
                currentIndex += totalReadingLength;
            }
            
            Model = model;
            return model;
        }
    }
}
